package com.ferry.jraft.rpc;

import com.alipay.remoting.BizContext;
import com.alipay.remoting.rpc.RpcServer;
import com.ferry.jraft.LifeCycle;
import com.ferry.jraft.impl.NodeImpl;
import com.ferry.jraft.model.dto.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author ferry
 * @create 2022/5/20 15:24
 * @description
 */
@Slf4j
public class RaftRpcServer implements LifeCycle {

    private NodeImpl node;
    private RpcServer server;

    public RaftRpcServer(NodeImpl node, int port) {
        server = new RpcServer(port, false, false);
        server.registerUserProcessor(new RaftUserProcessor() {
            @Override
            public Object handleRequest(BizContext bizCtx, Request request) throws Exception {
                return dispatchRequest(request);
            }
        });
        this.node = node;
    }

    private Response dispatchRequest(Request request) {
        switch (request.cmd) {
            case Request.REQUEST_VOTE: {
                return node.handleVoteRequest((VoteRequest) request);
            }
            case Request.APPENDE_ENTRIES: {
                return node.handleAppendEntriesRequest((AppendEntriesRequest) request);
            }
            case Request.CLIENT_REQUEST: {
                return node.handleClientRequest((ClientRequest) request);
            }
            case Request.CHANGE_PEERS_ADD: {

            }
            case Request.CHANGE_PEERS_REMOVE: {

            }
        }
        return null;
    }

    @Override
    public void init() throws Throwable {
        server.start();
    }

    @Override
    public void destroy() throws Throwable {
        server.shutdown();
    }


}
